package com.huitone.gddw.controller.worktable.paramconfigmanage;

import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.ServiceCodeDef;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.dao.entity.SvrNodeDef;
import com.huitone.gddw.log.Log;
import com.huitone.gddw.log.LogResult;
import com.huitone.gddw.log.LogType;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.IServiceCodeDefService;
import com.huitone.gddw.service.ISvrNodeDefService;
import com.huitone.gddw.service.dto.SvrNodeDefDTO;
import com.huitone.gddw.service.system.IRoleService;
import com.huitone.gddw.utils.Base64Utils;
import com.huitone.gddw.utils.SysLoginUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 业务端管理控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="svrNodeDef")
public class SvrNodeDefController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(SvrNodeDefController.class);
	
	private final static String STATUS_DEL = "2";
	
	@Autowired
	private ISvrNodeDefService svrNodeDefService;
	
	@Autowired
	private IServiceCodeDefService serviceCodeDefService;

	@Autowired
	private IRoleService roleService;
	
	/**
	 * 业务端管理查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<SvrNodeDefDTO> query(QueryPage<SvrNodeDef> page, HttpServletRequest request) {
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询业务端";
		Map<String, Object> params = new HashMap<String, Object>();
		String svrNode = request.getParameter("svrNode");
		String svrNodeName = request.getParameter("svrNodeName");
		String upflag = request.getParameter("upflag");
		String srvtype = request.getParameter("srvtype");
		params.put("svrNode", svrNode);
		params.put("svrNodeName", svrNodeName);
		params.put("upflag", upflag);
		params.put("srvtype", srvtype);
		page.setParams(params);
		QueryPage<SvrNodeDefDTO> result = null;
		try {
			result = svrNodeDefService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询业务端信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	/**
	 * 获取业务端信息
	 * @return svrNode svrNodeName
	 */
	@ResponseBody
	@RequestMapping(value="getSvrNode")
	public List<Map<String, Object>> getSvrNode(HttpSession session,String dicName) {
		List<Map<String, Object>> list = null;
		String userId = (String) session.getAttribute("userId");

		if ("1".equals(dicName) || dicName == "1") {
			list = svrNodeDefService.getSvrNode();
		} else {
			//		判断是否有查看所有数据的权限
			if (roleService.isRootAcsFlag(SysLoginUtil.getLoginUserId())) {
				list = svrNodeDefService.getSvrNode();
			} else {
				list = svrNodeDefService.getUnitSvrNode(userId);
			}
		}
		return list;
	}
	
	/**
	 * 更改业务端状态
	 * @param svrNode 业务端编码
	 * @param status 更改后状态
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus")
	public Message changeStatus(String svrNode, String status) {
		try {
			updateStatus(svrNode, status);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改业务端状态过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 更改业务端状态
	 * @param svrNode 业务端编码
	 * @param status 更改后状态
	 */
	private void updateStatus(String svrNode, String status) {
		SvrNodeDef entity = svrNodeDefService.selectByPrimaryKey(svrNode);
		entity.setStatus(status);
		svrNodeDefService.update(entity);
	}
	
	/**
	 * 修改页面数据准备
	 * @param svrNode 业务端编码
	 * @return SvrNodeDefDTO
	 */
	@ResponseBody
	@RequestMapping(value="toUpdate")
	public SvrNodeDefDTO toUpdate(String svrNode) {
		try {
			SvrNodeDefDTO entity = svrNodeDefService.selectForUpdate(svrNode);
			return entity;
		} catch (Exception e) {
			LOGGER.error("跳转修改页面过程中出现异常：" + e.getMessage(), e);
			return new SvrNodeDefDTO();
		}
	}
	
	/**
	 * 保存业务端信息
	 * @param entity SvrNodeDef
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	@Log(logType=LogType.UPDATE, content="添加业务端")
	public Message save(SvrNodeDef entity, HttpServletRequest request) {
		try {
			String lp = Base64Utils.encode(entity.getLoginPwd());
			if (lp.length() > 16) {
				return new Message(false, "接入登入密码长度过长，请重新设置！");
			}
			String lsp = Base64Utils.encode(entity.getLoginSvrPwd());
			if (lsp.length() > 16) {
				return new Message(false, "服务接入密码长度过长，请重新设置！");
			}
			List<SvrNodeDef> list = svrNodeDefService.selectBySvrNodeName(entity.getSvrNode(),entity.getSvrNodeName()); 
			if (list.size()>0) {
				return new Message(false, "该业务端名称已存在！");
			}
			svrNodeDefService.save(entity);
			return new Message(true, "保存成功！");
		} catch (Exception e) {
			LOGGER.error("保存业务端定义信息过程中出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return new Message(false, "保存失败！");
		}
	}
	
	/**
	 * 更新业务端信息
	 * @param entity SvrNodeDef
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="update")
	@Log(logType=LogType.UPDATE, content="修改业务端")
	public Message update(SvrNodeDef entity, HttpServletRequest request) {
		try {
			String lp = Base64Utils.encode(entity.getLoginPwd());
			if (lp.length() > 16) {
				return new Message(false, "接入登入密码长度过长，请重新设置！");
			}
			String lsp = Base64Utils.encode(entity.getLoginSvrPwd());
			if (lsp.length() > 16) {
				return new Message(false, "服务接入密码长度过长，请重新设置！");
			}
			List<SvrNodeDef> list = svrNodeDefService.selectBySvrNodeName(entity.getSvrNode(),entity.getSvrNodeName()); 
			if (list.size()>0) {
				return new Message(false, "该业务端名称已存在！");
			}
			
			SvrNodeDef svrNodeDef = svrNodeDefService.selectByPrimaryKey(entity.getSvrNode());
			svrNodeDef.setSvrNodeName(entity.getSvrNodeName());
//			svrNodeDef.setAccessMode(entity.getAccessMode());
			svrNodeDef.setUpflag(entity.getUpflag());
			svrNodeDef.setConNum(entity.getConNum());
			svrNodeDef.setLoginUser(entity.getLoginUser());
			svrNodeDef.setLoginPwd(entity.getLoginPwd());
			svrNodeDef.setServerIp(entity.getServerIp());
			svrNodeDef.setServerPort(entity.getServerPort());
			svrNodeDef.setLoginSvrUser(entity.getLoginSvrUser());
			svrNodeDef.setLoginSvrPwd(entity.getLoginSvrPwd());
			svrNodeDef.setSendPort(entity.getSendPort());
			svrNodeDef.setStatus(entity.getStatus());
			svrNodeDef.setDesc(entity.getDesc());
			svrNodeDef.setMaxFlux(entity.getMaxFlux());
			svrNodeDef.setAcceptReport(entity.getAcceptReport());
			svrNodeDef.setAcceptMo(entity.getAcceptMo());
			svrNodeDef.setSrvtype(entity.getSrvtype());
			svrNodeDef.setSmTypecheck(entity.getSmTypecheck());//是否短信类型检测:0 :是，1否
			svrNodeDefService.updateByPrimaryKey(svrNodeDef);
			return new Message(true, "修改成功！");
		} catch (Exception e) {
			LOGGER.error("修改业务端信息过程中出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return new Message(false, "修改失败！");
		}
	}
	
	/**
	 * 删除业务端信息
	 * @param svrNode 业务端编码
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete(String svrNode) {
		super.logType = SmLog.LOGTYPE_DELETE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]删除业务端";
		boolean isSuccess = true;
		String msg;
		try {
			updateStatus(svrNode, STATUS_DEL);
			msg = "删除成功！";
		} catch (Exception e) {
			LOGGER.error("删除业务端信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "删除失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 短信设置
	 * @param svrNode 业务端编码
	 * @param serviceCodes 短信业务编码
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="updateServiceCode")
	public Message updateServiceCode(String svrNode, String serviceCodes) {
		List<String> listServiceCode = StringUtils.isBlank(serviceCodes) ? new ArrayList<String>() : Arrays.asList(serviceCodes.split(","));
		List<String> listAllCode = new ArrayList<String>(); 	// 保存该业务的所有短信业务
		List<String> listSave = new ArrayList<String>(); 		// 存储需要保存的短信业务编码
		List<String> listDel = new ArrayList<String>(); 		// 存储需要删除的短信业务编码
		try {
			List<ServiceCodeDef> listServiceCodeDef = serviceCodeDefService.getBySvrNode(svrNode);
			for (ServiceCodeDef serviceCodeDef : listServiceCodeDef) {
				listAllCode.add(serviceCodeDef.getServiceCode());
			}
			for (String serviceCode : listServiceCode) {
				if (!listAllCode.contains(serviceCode)) {
					listSave.add(serviceCode);
				}
			}
			for (String serviceCode : listAllCode) {
				if (!listServiceCode.contains(serviceCode)) {
					listDel.add(serviceCode);
				}
			}
			svrNodeDefService.updateServiceCode(svrNode, listSave, listDel);
			return new Message(true, "短信设置成功！");
		} catch (Exception e) {
			LOGGER.error("短信设置过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "短信设置失败！");
		}
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "业务端信息表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
		List<SvrNodeDefDTO> list = svrNodeDefService.getRecord(params);
		if (null == list || 0 == list.size()) {
			list.add(new SvrNodeDefDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	
	/**
	 * 更改是否为白名单
	 * @param svrNode
	 * @param srvtype
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="changeIsWhite")
	public Message changeIsWhite(String svrNode, String srvtype) {
		try {
			SvrNodeDef entity = svrNodeDefService.selectByPrimaryKey(svrNode);
			entity.setSrvtype(srvtype);
			svrNodeDefService.update(entity);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改白名单过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
}
